package com.example.moilapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.example.moilapp.service.Moil_Image_Load_Service;
import com.example.moilapp.service.Moil_Image_Save_Service;
import com.example.moilapp.service.Moil_Pendingtask_Service;
import com.example.moilapp.signature.Moil_CaptureSignature;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Moil_Job_Detail extends Activity{
	
	public static final int SIGNATURE_ACTIVITY = 1;
	
	private ImageView myImage;
	
	TextView data_jobno;
	TextView data_dono;
	
	int jobid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.moil_service_report_screen);
		
		//PRIYAN
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			int id = extras.getInt("jobid");
			jobid = id;
			String orgname_str = extras.getString("orgname");
			String com_address_str = extras.getString("OrderAddr");
			String data_jobno_str = extras.getString("jobno");
			String data_dono_str = extras.getString("dono");
			String data_date_str = extras.getString("date");
			String data_pageno_str = extras.getString("pageno");
			String data_prpby_str = extras.getString("prpby");
			int data_totpack_str = extras.getInt("totpack");
			String data_billto_str = extras.getString("billto");
			String data_shipto_str = extras.getString("shipto");
			String data_mawb_str = extras.getString("mawb");
			String data_hawb_str = extras.getString("hawb");
			String data_flt_str = extras.getString("flt");
			String pic = extras.getString("pic");
			
			Log.e("extras.getString(arrdate)", extras.getString("arrdate"));
			Log.e("extras.getString(arrdate)", ""+extras.getString("arrdate").replace("-", "").equals("2001-01-01"));
			
			String data_arrdate_str = (convertDate(extras.getString("arrdate")).equals("2001-01-01")?"NA":convertDate(extras.getString("arrdate")));
			String data_origin_str = extras.getString("origin");
			int data_nopack_str = extras.getInt("nopack");
			String data_weight_str = extras.getString("weight");
			String data_vessel_str = extras.getString("vessel");
			String data_shipper_str = extras.getString("shipper");
			String data_des_goods_str = extras.getString("desgoods");
			String data_delivery_address_str = extras.getString("deladdr");
			String data_client_name = extras.getString("clientName");
			
			String[] clntSplit = data_client_name.split("-");
			
			String JustClientName = clntSplit[1];
			
			String fixednorDate = convertDate(data_date_str);
			//String fixedarrDate = convertDate(data_arrdate_str);

			TextView com_address = (TextView) findViewById(R.id.com_address);
			data_jobno = (TextView) findViewById(R.id.data_jobno);
			data_dono = (TextView) findViewById(R.id.data_dono);
			TextView data_date = (TextView) findViewById(R.id.data_date);
			TextView data_pageno = (TextView) findViewById(R.id.data_pageno);
			TextView data_prpby = (TextView) findViewById(R.id.data_prpby);
			TextView data_totpack = (TextView) findViewById(R.id.data_totpack);
			TextView data_billto = (TextView) findViewById(R.id.data_billto);
			TextView data_shipto = (TextView) findViewById(R.id.data_shipto);
			TextView data_mawb = (TextView) findViewById(R.id.data_mawb);
			TextView data_hawb = (TextView) findViewById(R.id.data_hawb);
			TextView data_flt = (TextView) findViewById(R.id.data_flt);
			TextView data_arrdate = (TextView) findViewById(R.id.data_arrdate);
			TextView data_origin = (TextView) findViewById(R.id.data_origin);
			TextView data_nopack = (TextView) findViewById(R.id.data_nopack);
			TextView data_weight = (TextView) findViewById(R.id.data_weight);
			TextView data_vessel = (TextView) findViewById(R.id.data_vessel);
			TextView data_shipper = (TextView) findViewById(R.id.data_shipper);
			TextView data_des_goods = (TextView) findViewById(R.id.data_des_goods);
			TextView data_delivery_address = (TextView) findViewById(R.id.data_delivery_address);

			com_address.setText(JustClientName+"\n"+com_address_str);
			data_jobno.setText(data_jobno_str);
			data_dono.setText(data_dono_str);
			data_date.setText(fixednorDate);
			data_pageno.setText(data_pageno_str);
			data_prpby.setText(data_prpby_str);
			//data_totpack.setText(""+data_totpack_str);
			data_totpack.setText((pic.equals(null))?"NA":pic);
			data_billto.setText(data_billto_str);
			data_shipto.setText(data_shipto_str);
			data_mawb.setText((data_mawb_str.equals(""))?"NA":data_mawb_str);
			data_hawb.setText(data_hawb_str);
			data_flt.setText(data_flt_str);
			data_arrdate.setText(data_arrdate_str);
			data_origin.setText(data_origin_str);
			data_nopack.setText(""+data_nopack_str);
			data_weight.setText(data_weight_str);
			data_vessel.setText(data_vessel_str);
			data_shipper.setText(data_shipper_str);
			data_des_goods.setText(data_des_goods_str);
			data_delivery_address.setText(data_delivery_address_str);

		}
		
		//PRIYAN
		
		Moil_Image_Load_Service mps = new Moil_Image_Load_Service(Moil_Job_Detail.this,data_jobno.getText().toString(),data_dono.getText().toString(),""+jobid);
		mps.execute(new String[] {"http://t2a1.cloudapp.net/TrafficWorkflow/TraficWorkflowWebService.asmx"});
	    
		
		//Get Image Name From the passing JobNo
		
		ContextWrapper cw = new ContextWrapper(getApplicationContext());
		File directory = cw.getDir(
				getResources().getString(R.string.external_dir),
				Context.MODE_PRIVATE);
		
		String current = data_jobno.getText().toString()+"_"+data_dono.getText().toString()+ ".png";
		
		//File imgFile = new  File("/sdcard/Images/test_image.png");
		
		/*File imgFile = new File(directory, current);
		
		if(imgFile.exists()){

		    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

		    myImage = (ImageView) findViewById(R.id.signature_imageview);
		    Button signature_dotline = (Button) findViewById(R.id.signature_dotline);
		    
		    signature_dotline.setVisibility(View.GONE);
		    
		    myImage.setImageBitmap(myBitmap);
		    //Make Dotted Line Invisible
		}else{
			myImage = (ImageView) findViewById(R.id.signature_imageview);
			myImage.setVisibility(View.GONE);
		}*/
		
		Button btnsignature = (Button)findViewById(R.id.signature_dotline);
		
		btnsignature.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Moil_Job_Detail.this, Moil_CaptureSignature.class); 
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle bundle = new Bundle();
				bundle.putString("jobid",""+jobid);
				bundle.putString("jobno",data_jobno.getText().toString());
				bundle.putString("dono",data_dono.getText().toString());
				intent.putExtras(bundle);
				startActivityForResult(intent,SIGNATURE_ACTIVITY);
				
			}
		});
		
	}
	
	 protected void onActivityResult(int requestCode, int resultCode, Intent data)
	    {
	        switch(requestCode) {
	        case SIGNATURE_ACTIVITY: 
	            if (resultCode == RESULT_OK) {
	 
	                Bundle bundle = data.getExtras();
	                String status  = bundle.getString("status");
	                //String encodedStr  = bundle.getString("encodedStr");
	                if(status.equalsIgnoreCase("done")){
	                    Toast toast = Toast.makeText(this, "Signature capture successful!", Toast.LENGTH_SHORT);
	                    //toast.setGravity(Gravity.TOP, 105, 50);
	                    toast.show();
	                }
	                
	                Log.e("data_jobno.getText()",data_jobno.getText().toString());
	                Log.e("data_dono.getText()",data_dono.getText().toString());
	               
	                
	                //PRIYAN SET Image
	        		
	        		ContextWrapper cw = new ContextWrapper(getApplicationContext());
	        		File directory = cw.getDir(
	        				getResources().getString(R.string.external_dir),
	        				Context.MODE_PRIVATE);
	        		
	        		String current = data_jobno.getText().toString()+"_"+data_dono.getText().toString()+ ".png";
	        		
	        		//File imgFile = new  File("/sdcard/Images/test_image.png");
	        		File imgFile = new File(directory, current);
	        		
	        		//PRIYAN IMAGE START
	        		
	        		Bitmap  newBitmap= null;
	        		
	        		try {
	    				FileOutputStream mFileOutStream = new FileOutputStream(imgFile);

	    				newBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
	    				mFileOutStream.flush();
	    				mFileOutStream.close();
	    				String url = Images.Media.insertImage(getContentResolver(),
	    						newBitmap, "title", null);
	    				Log.v("log_tag", "url: " + url);
	    				

	    			} catch (Exception e) {
	    				Log.v("log_tag", e.toString());
	    			}
	    			
	    			String converted = encodeTobase64(newBitmap);
	        		
	    			Log.e("encodedStr", converted);
	    			
	        		//PRIYAN IMAGE END
	        		
	        		if(imgFile.exists()){

	        		    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

	        		    myImage = (ImageView) findViewById(R.id.signature_imageview);
	        		    Button signature_dotline = (Button) findViewById(R.id.signature_dotline);
	        		    
	        		    signature_dotline.setVisibility(View.GONE);
	        		    
	        		    myImage.setImageBitmap(myBitmap);
	        		    //Make Dotted Line Invisible
	        		}else{
	        			myImage = (ImageView) findViewById(R.id.signature_imageview);
	        			myImage.setVisibility(View.GONE);
	        		}
	        		
	        		//PRIYAN Set Image
	                
	                //Moil_Image_Save_Service mps = new Moil_Image_Save_Service(Moil_Job_Detail.this,data_jobno.getText().toString(),data_dono.getText().toString(),converted);
	        		//mps.execute(new String[] {"http://t2a1.cloudapp.net/TrafficWorkflow/TraficWorkflowWebService.asmx"});
	        	    
	            }
	            break;
	        }
	 
	    }  
	 
	 private String convertDate(String inDate){

			SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
			Date dateObj=null;;
			try {
				dateObj = curFormater.parse(inDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); 

			String newDateStr = postFormater.format(dateObj); 

			return newDateStr;
		}
	 
	 public static String encodeTobase64(Bitmap image)
		{
		    Bitmap immagex=image;
		    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		    immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
		    byte[] b = baos.toByteArray();
		    
		    String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
		    
		    //String imageEncoded = Base64.encodeBytes(b);

		    Log.e("LOOK", imageEncoded);
		    return imageEncoded;
		}
	
}
